import store from '@/store'

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} pid 父节点字段 默认 'pid'
 * @param {*} children 孩子节点字段 默认 'children'
 * @param {*} rootId 根Id 默认 0
 */
export function handleTree (data, id, pid, children, rootId) {
  id = id || 'id'
  pid = pid || 'pid'
  children = children || 'children'
  rootId = rootId || Math.min.apply(Math, data.map(item => { return item[pid] })) || 0
  //对源数据深度克隆
  const cloneData = JSON.parse(JSON.stringify(data))
  //循环所有项
  const treeData = cloneData.filter(father => {
    let branchArr = cloneData.filter(child => {
      //返回每一项的子级数组
      return father[id] === child[pid]
    });
    branchArr.length > 0 ? father.children = branchArr : '';
    //返回第一层
    return father[pid] === rootId;
  });
  return treeData != '' ? treeData : data;
}

// 生成树结构菜单
export const generateOptions = (params) => {
  let result = [];
  for (let param of params) {
    if (param.pid == 0) {//判断是否为顶层节点
      param.children = getchildsID(param.id, params);//获取子节点
      result.push(param);
    }
  }
  return result;
}

// 遍历子元素
export const getchildsID = (id, array) => {
  let childs = new Array();
  for (let arr of array) {
    if (arr.pid == id) {
      childs.push(arr)
    }
  }
  for (let child of childs) {//获取子节点的子节点
    let childscopy = getchildsID(child.id, array)//递归获取子节点
    if (childscopy.length > 0) {
      child.children = childscopy;
    }
  }
  return childs
}


/**
 * 根据时间登录提示语
 */
export const tipLoginWelcome = () => {
  let now = new Date(), hour = now.getHours()
  if (hour < 6) { return "凌晨好！" }
  else if (hour < 9) { return "早上好！" }
  else if (hour < 12) { return "上午好！" }
  else if (hour < 14) { return "中午好！" }
  else if (hour < 17) { return "下午好！" }
  else if (hour < 19) { return "傍晚好！" }
  else if (hour < 22) { return "晚上好！" }
  else { return "夜里好！" }
}

/**
 * 路由鉴权
 * @param {*} route 
 */
export const hasRoute = (route, routes) => routes.find(ro => ro.path == route.path) ? true : false


/**
 * 表格导出Excel
 * @param {*} columns 表头
 * @param {*} list 数据
 */
export const export2Excel = (columns, list) => {
  require.ensure([], () => {
    const { export_json_to_excel } = require('../excel/Export2Excel');
    let tHeader = []
    let filterVal = []
    console.log(columns)
    if (!columns) {
      return;
    }
    columns.forEach(item => {
      tHeader.push(item.title)
      filterVal.push(item.key)
    })
    const data = list.map(v => filterVal.map(j => v[j]))
    export_json_to_excel(tHeader, data, '数据列表');
  })
}


/**
 * 判断用户是否拥有操作权限
 * 根据传入的权限标识，查看是否存在用户权限标识集合
 * @param perms
 */
export function hasPermission (perms) {
  let hasPermission = false
  let permissions = store.state.permission.perms
  for (let i = 0, len = permissions.length; i < len; i++) {
    if (permissions[i] === perms) {
      hasPermission = true;
      break
    }
  }
  return hasPermission
}